import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Drawer, Modal, FormInstance } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage, connect, ConnectProps } from 'umi';
import type { ConnectState } from '@/models/connect';
import type { CurrentUser } from '@/models/user';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText, ProFormTextArea, ProFormSelect } from '@ant-design/pro-form';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import UpdateForm from './components/UpdateForm';
import MenuTree from './components/MenuTree';

import type { TableListItem } from './data.d';
import { queryData, updateData, addData, removeData, updateStatus } from './service';

/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');
  try {
    await addData({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: TableListItem) => {
  const hide = message.loading('正在配置');
  try {
    await updateData(fields);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeData({
      ids: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


const handleRemoveOne = async (selectedRow: TableListItem) => {
  const hide = message.loading('正在删除');
  if (!selectedRow) return true;
  try {
    let params = [selectedRow.id]
    await removeData({
      ids: params,
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


const handleUpdateStatus = async (id: string, status: string) => {
  const hide = message.loading('正在更新状态');
  try {
    await updateStatus(id, status);
    message.success('状态更新成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('状态更新失败，请重试');
    return false;
  }
};

export type GlobalTableProps = {
  currentUser?: CurrentUser;
} & Partial<ConnectProps>;

const TableList: React.FC<GlobalTableProps> = (props) => {
  const formTableRef = useRef<FormInstance>();
  const formRef = useRef<FormInstance>();
  const childref = useRef();

  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /** 分布更新窗口的弹窗 */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  //选中树形
  const [selectMenu, setSelectMenu] = useState<any>();

  //添加表单类型
  const [type, setType] = useState<any>('0');
  const [options, setOptions] = useState<any>();

  /** 国际化配置 */
  const intl = useIntl();
  const { currentUser } = props;

  useEffect(() => {
    const options = [
      { value: '0', label: '目录', },
      { value: '1', label: '菜单', },
      { value: '3', label: '外链', },
      { value: '4', label: 'iframe', },
    ]
    setOptions(options)
  }, []);




  const columns: ProColumns<TableListItem>[] = [
    {
      title: '菜单名称',
      dataIndex: 'name',
      tip: '菜单名称',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '请求路径',
      dataIndex: 'path',
      valueType: 'textarea',
    },
    {
      title: '类型',
      dataIndex: 'type',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '目录',
          status: 'Success',
        },
        1: {
          text: '菜单',
          status: 'Processing',
        },
        2: {
          text: '按钮',
          status: 'Processing',
        },
        3: {
          text: '外链',
          status: 'Processing',
        },
        4: {
          text: 'iframe',
          status: 'Processing',
        },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '启用',
          status: 'Success',
        },
        1: {
          text: '禁用',
          status: 'Processing',
        },
      },
    },
    {
      title: '排序',
      dataIndex: 'order_by',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '父级id',
      dataIndex: 'parent_id',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true,
      hideInForm: true,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      width: '220px',
      valueType: 'option',
      render: (_, record) => [
        <Button type="primary" size='small' key="config"
          style={{ display: currentUser?.authButton.includes('menu:edit') ? 'block' : 'none' }}
          onClick={() => {
            record.parent_name = selectMenu.name;
            record.parent_id = selectMenu.id;
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}>
          编辑
       </Button>,
        <Button type="primary" size='small' danger
          style={{ display: currentUser?.authButton.includes('menu:del') ? 'block' : 'none' }}
          onClick={async () => {
            Modal.confirm({
              title: '删除任务',
              content: '确定删除该任务吗？',
              okText: '确认',
              cancelText: '取消',
              onOk: () => {
                const success = handleRemoveOne(record);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                  childref.current._childFn();
                }
              },
            });
          }}>
          删除
      </Button>,
        <Button type="primary" size='small' style={{ display: (record.status == '0' && currentUser?.authButton.includes('menu:status')) ? 'block' : 'none' }} danger onClick={() => {
          const success = handleUpdateStatus(record.id, '1');
          if (success) {
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}>
          禁用
    </Button>,
        <Button type="primary" size='small' style={{ display: (record.status == '1' && currentUser?.authButton.includes('menu:status')) ? 'block' : 'none' }} onClick={() => {
          const success = handleUpdateStatus(record.id, '0');
          if (success) {
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}>
          启用
  </Button>,
      ],
    },
  ];


  return (
    <PageContainer>
      <div style={{ width: '20%', float: 'left' }}>
        <MenuTree myFef={childref} onSelect={async (value: any) => {
          setSelectMenu(value);
          //查询列表数据
          if (actionRef.current) {
            formTableRef.current.setFieldsValue({
              parent_id: value.id
            });
            formTableRef.current.submit();
          }
        }}></MenuTree>
      </div>
      <div style={{ width: '79%', float: 'right' }}>
        <ProTable<TableListItem>
          headerTitle='菜单信息'
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="id"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              style={{ display: currentUser?.authButton.includes('menu:add') ? 'block' : 'none' }}
              onClick={() => {
                if (selectMenu.id == '' || selectMenu.id == null) {
                  message.warning('请选择左侧父级节点');
                } else {
                  console.log('-----')
                  console.log(selectMenu.type)
                  if (selectMenu.type == '1') {
                    const options = [
                      { value: '2', label: '按钮', },
                    ]
                    setOptions(options);
                    setType('2');
                    console.log("+++:::" + type)
                    formRef.current.setFieldsValue({
                      type: '2'
                    });
                  } else {
                    const options = [
                      { value: '0', label: '目录', },
                      { value: '1', label: '菜单', },
                      { value: '3', label: '外链', },
                      { value: '4', label: 'iframe', },
                    ]
                    setOptions(options)
                    setType('0');
                    formRef.current.setFieldsValue({
                      type: '0'
                    });
                  }
                  formRef.current.setFieldsValue({
                    parent_name: selectMenu.name
                  });
                  console.log(type)
                  handleModalVisible(true);
                }
              }}
            >
              <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="新建" />
            </Button>,
          ]}
          request={
            (params, sorter, filter) => queryData({ ...params, parent_id: selectMenu.id }).then(res => {
              const result = {
                data: res.data.rows,
                total: res.data.total,
                success: true
              }
              return result
            })
          }
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />
      </div>
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="已选择" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            style={{ display: currentUser?.authButton.includes('menu:del') ? 'block' : 'none' }}
            onClick={async () => {
              Modal.confirm({
                title: '删除任务',
                content: '确定删除该任务吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: () => {
                  const success = handleRemove(selectedRowsState);
                  if (success) {
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                    childref.current._childFn();
                  }
                },
              });
            }}
          >
            <FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="批量删除" />
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title={intl.formatMessage({
          id: '新建菜单',
          defaultMessage: '新建菜单',
        })}
        width="600px"
        formRef={formRef}
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd({ ...value, parent_id: selectMenu.id, level_num: selectMenu.level_num, menu_cascade: selectMenu.menu_cascade } as TableListItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
            formRef.current?.resetFields();
            childref.current._childFn();
          }
        }}
      >
        <ProFormText
          label={intl.formatMessage({
            id: '父节点名称',
            defaultMessage: '父节点名称',
          })}
          disabled
          width="xl"
          name="parent_name"
          placeholder="请输入父节点名称"
        />
        <ProFormSelect
          options={options}
          fieldProps={{
            onChange: (val) => {
              setType(val);
            }
          }}
          // initialValue="0"
          width="md"
          name="type"
          label='选择类型'
          rules={[
            {
              required: true,
              message: '选择类型',
            },
          ]}
        />
        <ProFormText
          label='菜单名称'
          rules={[
            {
              required: true,
              message: '请输入菜单名称',
            },
          ]}
          width="xl"
          name="name"
          placeholder="请输入菜单名称"
        />
        <ProFormText
          label='路由地址'
          // rules={[
          //   {
          //     required: true,
          //     message: '请输入路由地址',
          //   },
          // ]}
          width="xl"
          name="path"
          placeholder="请输入路由地址"
          hidden={(type == '0' || type == '1' || type == '3' || type == '4') ? false : true}
        />
        <ProFormText
          label='重定向地址'
          width="xl"
          name="redirect"
          placeholder="请输入重定向地址"
          hidden={(type == '0') ? false : true}
        />
        <ProFormText
          label='组件路径'
          width="xl"
          name="component"
          hidden={type != 1 ? true : false}
          placeholder="请输入组件路径"
        />
        <ProFormText
          label='权限标识'
          width="xl"
          name="permission"
          placeholder="请输入权限标识"
          hidden={(type == '1' || type == '2') ? false : true}
        />
        <ProFormText
          label='菜单图标'
          width="xl"
          name="icon"
          placeholder="请输入菜单图标"
          hidden={(type == '0' || type == '1' || type == '3' || type == '4') ? false : true}
        />
        <ProFormText
          label={intl.formatMessage({
            id: '排序',
            defaultMessage: '排序',
          })}
          rules={[
            {
              required: true,
              message: '排序',
            },
          ]}
          width="xl"
          name="order_by"
          placeholder="请输入排序"
        />
        <ProFormTextArea width="xl" name="remark" label='备注'
          placeholder="请输入备注"
        />
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate({ ...value, id: currentRow?.id });
          // const success = await handleUpdate({...value,id:currentRow?.id});
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
            childref.current._childFn();
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<TableListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<TableListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

// export default TableList;
export default connect(({ user, loading }: ConnectState) => ({
  currentUser: user.currentUser,
}))(TableList);